<template>
  <view class="page-container">
    <!-- 固定头部导航 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-bar">
        <view class="left" @tap="goBack">
          <text class="back-icon">〈</text>
        </view>
        <view class="title-container">
          <view class="avatar-title">
            <image class="avatar" :src="deviceInfo?.icon" mode="aspectFill" />
            <view class="title-info">
              <text class="name">{{ deviceInfo?.name }}</text>
              <text class="creator">@{{ deviceInfo?.creatorName }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 可滚动的消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-into-view="lastMessageId" 
      :scroll-with-animation="true"
      :style="{ top: `calc(${statusBarHeight}px + 88rpx)` }"
      @scrolltoupper="loadMoreHistory"
    >
      <block v-if="messages.length">
        <template v-for="(msg, index) in messages" :key="msg.id">
          <!-- 居中的时间戳 -->
          <view v-if="shouldShowTimestamp(msg, messages[index - 1])" class="time-stamp-wrapper">
            <view class="time-stamp">{{ formatTime(msg.timestamp) }}</view>
          </view>

          <!-- 消息气泡 -->
          <view :id="`msg-${msg.id}`" :class="['message-item', msg.role]">
            <image class="avatar" :src="msg.role === 'assistant' ? deviceInfo?.icon : userInfo?.avatar"
              mode="aspectFill" />
            <view class="content">{{ msg.content }}</view>
          </view>
        </template>
      </block>
    </scroll-view>

    <!-- 固定底部输入区 -->
    <view class="fixed-footer">
      <view class="input-box">
        <input v-model="inputContent" class="input" type="text" placeholder="发送消息..." confirm-type="send"
          @confirm="sendMessage" />
        <button class="send-btn" :class="{ active: inputContent }" @tap="sendMessage">
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
	import {
		ref,
		computed,
		nextTick,
		watch
	} from 'vue' // 添加 watch 导入
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/stores/modules/user'
	import {
		useChatStore
	} from '@/stores/modules/chat'
	import {
		useDeviceStore
	} from '@/stores/modules/device'
	import {
		system
	} from '@/utils'

	const statusBarHeight = system.getStatusBarHeight()
	const userStore = useUserStore()
	const chatStore = useChatStore()
	const deviceStore = useDeviceStore()

	// 状态管理
	const userInfo = computed(() => userStore.userInfo)
	const messages = computed(() => chatStore.messages)
	const inputContent = ref('')
	const deviceInfo = ref(null)
	const lastMessageId = ref('')
	const voiceConfig = ref(null)
	const chatApi = ref(null)

	// 监听消息变化
	watch(messages, (newMessages) => {
		console.log('Messages updated:', newMessages)
		nextTick(() => {
			scrollToBottom()
		})
	}, {
		deep: true
	})

	// 发送消息
	const sendMessage = async () => {
		const content = inputContent.value?.trim()
		if (!content || chatStore.loading) return

		try {
			console.log('准备发送消息:', {
				content,
				deviceId: deviceInfo.value?.id,
				timestamp: Date.now(),
				voiceConfig: deviceInfo.value?.voiceConfig,
				chatApi: deviceInfo.value?.chatApi
			})

			const message = {
				message: content,
				sessionId: deviceInfo.value?.id?.toString(),
				voiceConfig: deviceInfo.value?.voiceConfig,
				chatApi: deviceInfo.value?.chatApi
			}

			// 清空输入框
			inputContent.value = ''

			// 发送消息并等待响应
			await chatStore.sendMessage(message)

			console.log('消息发送成功')

		} catch (error) {
			console.error('发送失败:', error)
			uni.showToast({
				title: '发送失败',
				icon: 'none'
			})
		}
	}

	// 滚动到底部
	const scrollToBottom = () => {
		if (messages.value?.length) {
			lastMessageId.value = `msg-${messages.value[messages.value.length - 1].id}`
			console.log('Scrolling to message:', lastMessageId.value)
		}
	}

	// 初始化聊天
	onLoad((options) => {
		console.log('Chat page loaded with options:', options)
		initChat(parseInt(options.id))
	})

	// 初始化聊天 方法
	const initChat = async (deviceId) => {
		if (!deviceId) {
			uni.showToast({
				title: '无效的设备ID',
				icon: 'none'
			})
			return
		}

		try {
			console.log('Initializing chat with device ID:', deviceId)
			chatStore.setCurrentDeviceId(deviceId)

			const devices = await deviceStore.loadPrivateDevices()
			const device = devices.find(d => d.id === deviceId)

			if (!device) {
				throw new Error('设备不存在')
			}
			console.log('Found device:', device)
			deviceInfo.value = device

			// 如果没有历史消息，添加智能体的自我介绍
			if (!chatStore.messages.length) {
				// 直接添加一条AI的自我介绍消息
				const introMessage = {
					id: Date.now(),
					role: 'assistant', // 修改为 assistant 角色
					content: device.description,
					timestamp: Date.now()
				}
				chatStore.addMessage(introMessage)
			}

		} catch (error) {
			console.error('初始化失败:', error)
			uni.showToast({
				title: '初始化失败',
				icon: 'none'
			})
		}
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}

	// 加载更多历史记录
	const loadMoreHistory = async () => {
		if (chatStore.loading || !deviceInfo.value) return

		try {
			const page = Math.floor(messages.value.length / 20) + 1
			await chatStore.getMessages(deviceInfo.value.id, page, 20)
		} catch (error) {
			console.error('加载更多消息失败:', error)
		}
	}

	// 格式化时间
	const formatTime = (timestamp) => {
		if (!timestamp) return ''
		const date = new Date(timestamp)
		return date.toLocaleTimeString('zh-CN', {
			hour: '2-digit',
			minute: '2-digit'
		})
	}

	// 是否显示时间戳
	// 修改时间显示逻辑
	const shouldShowTimestamp = (currentMsg, prevMsg) => {
	  if (!currentMsg?.timestamp) return false
	  if (!prevMsg?.timestamp) return true // 显示第一条消息的时间戳
	  
	  // 修改为2分钟间隔显示时间戳
	  return currentMsg.timestamp - prevMsg.timestamp > 2 * 60 * 1000
	}


	// 消息列表监听
	watch(() => messages.value, (newMessages) => {
		console.log('Messages updated:', newMessages);
	}, {
		deep: true
	});
</script>

<style lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #f7f7f7;
  
  // 固定头部
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    
    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      background: #fff;
      border-bottom: 1px solid #eee;

      .left {
        margin-right: 20rpx;

        .back-icon {
          font-size: 36rpx;
          color: #333;
        }
      }

      .title-container {
        flex: 1;

        .avatar-title {
          display: flex;
          align-items: center;

          .avatar {
            width: 72rpx;
            height: 72rpx;
            border-radius: 50%;
            margin-right: 16rpx;
            background: #f5f6f7;
          }

          .title-info {
            display: flex;
            flex-direction: column;
            justify-content: center;

            .name {
              font-size: 32rpx;
              font-weight: 500;
              color: #333;
              line-height: 1.2;
            }

            .creator {
              font-size: 24rpx;
              color: #999;
              line-height: 1.2;
            }
          }
        }
      }
    }
  }

  // 消息列表区域
  .message-list {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(112rpx + env(safe-area-inset-bottom));
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    background: #f7f7f7;
    padding: 20rpx 30rpx;

    // 时间戳
    .time-stamp-wrapper {
      display: flex;
      justify-content: center;
      padding: 16rpx 0;
      
      .time-stamp {
        padding: 8rpx 24rpx;
        font-size: 24rpx;
        color: #fff;
        background: rgba(0, 0, 0, 0.15);
        border-radius: 24rpx;
        text-align: center;
      }
    }

    // 消息项
    .message-item {
      display: flex;
      margin-bottom: 30rpx;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        flex-shrink: 0;
        background: #f5f6f7;
      }

      .content {
        max-width: 60%;
        padding: 20rpx 24rpx;
        border-radius: 12rpx;
        font-size: 28rpx;
        margin: 0 20rpx;
        word-break: break-all;
        line-height: 1.5;
      }

      // 用户消息
      &.user {
        flex-direction: row-reverse;

        .content {
          margin-right: 24rpx;
          background: #007AFF;
          color: #fff;
          border-radius: 16rpx 2rpx 16rpx 16rpx;
        }

        .avatar {
          margin-right: 50rpx;
        }
      }

      // AI助手消息
      &.assistant {
        .content {
          margin-left: 24rpx;
          background: #fff;
          color: #333;
          border-radius: 2rpx 16rpx 16rpx 16rpx;
        }

        .avatar {
          margin-left: 0rpx;
        }
      }
    }
  }

  // 底部输入区
  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    
    .input-box {
      padding: 20rpx;
      background: #f7f7f7;
      display: flex;
      align-items: center;
      border-top: 1px solid #eee;
      padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

      .input {
        flex: 1;
        height: 72rpx;
        background: #fff;
        border-radius: 36rpx;
        padding: 0 30rpx;
        font-size: 28rpx;
      }

      .send-btn {
        width: 120rpx;
        height: 72rpx;
        line-height: 72rpx;
        text-align: center;
        margin-left: 20rpx;
        border-radius: 36rpx;
        font-size: 28rpx;
        background: #f0f0f0;
        color: #999;
        padding: 0;
        border: none;

        &.active {
          background: #007AFF;
          color: #fff;
        }

        &::after {
          border: none;
        }
      }
    }
  }
}
</style>